/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.active;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.active.ActiveListAdapter.AdapterCallBack;
import com.tstudy.laoshibang.active.DictionaryAdapter.ActionCallBack;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.base.IndexActivity;
import com.tstudy.laoshibang.event.ActiveLoveEvent;
import com.tstudy.laoshibang.event.ActiveViewEvent;
import com.tstudy.laoshibang.event.ChangeGroupEvent;
import com.tstudy.laoshibang.manager.CategoryManager;
import com.tstudy.laoshibang.manager.CityManager;
import com.tstudy.laoshibang.manager.DictionaryManager;
import com.tstudy.laoshibang.mode.Active;
import com.tstudy.laoshibang.mode.Adverts;
import com.tstudy.laoshibang.mode.Category;
import com.tstudy.laoshibang.mode.City;
import com.tstudy.laoshibang.mode.Dictionary;
import com.tstudy.laoshibang.mode.request.Conds;
import com.tstudy.laoshibang.mode.response.ActiveCategoryResponse;
import com.tstudy.laoshibang.mode.response.ActiveListResponse;
import com.tstudy.laoshibang.mode.response.CommunityListResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressWarnings("deprecation")
@SuppressLint("InflateParams")
@EFragment(R.layout.active_list)
public class ActiveListFragment extends BaseFragment{
	static String TAG = "active_list";
	public ActiveListFragment() {
		super();
	}
	
	@ViewById(R.id.active_list_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.active_list_title_layout)
	RelativeLayout mTitleLayout;
	
	@ViewById(R.id.active_list_title)
	TextView mTitleTxt;
	
	@ViewById(R.id.active_list_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.active_list_list)
	PullToRefreshListView mPullToRefreshListView;
	
	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	ActiveListAdapter mActiveListAdapter;
	RelativeLayout mHeaderLayout;
	TextView mCategoryTxt;
	TextView mPriceTxt;
	TextView mLocationTxt;
	RelativeLayout mCategoryLayout;
	RelativeLayout mPriceLayout;
	RelativeLayout mLocationLayout;
	LinearLayout mViewPagerSelectLayout;
	ViewPager mViewPager;
	ImageView mEmptyView;
	
	RelativeLayout mEmptyLayout;
	ListItemPageAdapter mPageAdapter;
	
	Dictionary mSelectProvince;
	Category mSelectCategory;
	Dictionary mSelectPrice;
	public static final int BANNER_DURATION = 3000;
	int mCurrentPosition = 0;
	List<View> mViewList = new ArrayList<View>();
	List<Active> mActives = new ArrayList<Active>();
	List<Adverts> mAdverts = new ArrayList<Adverts>();
	List<Category> mCategorys = new ArrayList<Category>();
	
	@StringRes(R.string.select_all)
	String mSelectAllStr;
	String mSelectAllCode = "-1";
	int mSelectAllKey = -1;

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = ((BaseActivity)BaseApplication.mCurrentActivity).getFragmentByTag(TAG);
		if(fragment == null){
			fragment = Fragment.instantiate(BaseApplication.mContext,ActiveListFragment_.class.getName(),args);
		}
		((BaseActivity)BaseApplication.mCurrentActivity).addInTab(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			if (BaseApplication.mCurrentGroup != null) {
				mTitleTxt.setText(BaseApplication.mCurrentGroup.name +CONSTANT.GROUP_SEPEREATE + BaseApplication.getResString(R.string.active_list_title));
			}
			mRootLayout.setOnClickListener(null);
			initHeaderView();
			mPageAdapter = new ListItemPageAdapter();
			mViewPager.setAdapter(mPageAdapter);
			mViewPager.setOnPageChangeListener(mPageAdapter);
			mActiveListAdapter = new ActiveListAdapter();
			mPullToRefreshListView.setAdapter(mActiveListAdapter);
			mActiveListAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onAvatorClick(int activeId,int position) {
					ActiveDetailFragment.add(mFragmentId,activeId,position);
				}
				@Override
				public void onLoveClick(Active active, int position,TextView view) {
					loveAction(active,CONSTANT.ASSO_TYPE_ACTIVE,active.isPraise==0?CONSTANT.UNLOVE_ACTION:CONSTANT.LOVE_ACTION,view);
				}
			});
			mPullToRefreshListView.getRefreshableView().addHeaderView(mHeaderLayout);
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getActiveList();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getActiveList();
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getActiveList();
				}
			});
		}
	}
	public void fillAdverts(){
		mViewList.clear();
		int size = mAdverts.size();
		mEmptyView.getLayoutParams().height = BaseApplication.mScreenWidth/2;
		if (size > 0) {
			mViewPager.setVisibility(View.VISIBLE);
		}
		for (int i = 0; i < size; i++) {
			final Adverts each = mAdverts.get(i);
			RelativeLayout layout = (RelativeLayout) mInflater.inflate(R.layout.list_header_pager, null);
			ImageView img = (ImageView) layout.findViewById(R.id.list_header_pager_img);
			TextView title = (TextView) layout.findViewById(R.id.list_header_pager_title);
			ImageView leftIcon = (ImageView) layout.findViewById(R.id.list_header_pager_left_icon);
			ImageView rightIcon = (ImageView) layout.findViewById(R.id.list_header_pager_right_icon);
			if (i == 0) {
				if (size == 1) {
					leftIcon.setVisibility(View.GONE);
					rightIcon.setVisibility(View.GONE);
				}else{
					leftIcon.setVisibility(View.GONE);
					rightIcon.setVisibility(View.VISIBLE);
				}
			}else if(i == size -1){
				leftIcon.setVisibility(View.VISIBLE);
				rightIcon.setVisibility(View.GONE);
			}else{
				leftIcon.setVisibility(View.VISIBLE);
				rightIcon.setVisibility(View.VISIBLE);
			}
			HttpManager.getInstance().loadCommonImage(img,mAdverts.get(i).imgIdxName + CommonUtil.buildCropUrl(BaseApplication.mScreenWidth,BaseApplication.mScreenWidth/2));
			title.setText(mAdverts.get(i).title);
			mViewList.add(layout);
			img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (each.isRedirect == 1) {
					}else{
						ActiveDetailFragment.add(mFragmentId,each.assoId,-1);
					}
				}
			});
			
//			fillSelectLayout(mViewPagerSelectLayout, i);
			if (mIsLoading) {
				
			}
		}
		mPageAdapter.setData(mViewList);
		addCallBacks();
	}
	
	@SuppressLint("InflateParams")
	public void initHeaderView(){
		mHeaderLayout = (RelativeLayout) mInflater.inflate(R.layout.active_list_header, null);
		mViewPager = (ViewPager) mHeaderLayout.findViewById(R.id.active_list_header_viewpage);
		mEmptyView = (ImageView) mHeaderLayout.findViewById(R.id.active_list_header_empty_view);
		mViewPager.getLayoutParams().height = BaseApplication.mScreenWidth/2;
		mEmptyView.getLayoutParams().height = BaseApplication.mScreenWidth/2;
		mEmptyLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.active_list_empty_layout);
		mViewPagerSelectLayout = (LinearLayout) mHeaderLayout.findViewById(R.id.active_list_header_select_layout);
		mCategoryTxt = (TextView) mHeaderLayout.findViewById(R.id.active_list_header_filter_category);
		mPriceTxt = (TextView) mHeaderLayout.findViewById(R.id.active_list_header_filter_price);
		mLocationTxt = (TextView) mHeaderLayout.findViewById(R.id.active_list_header_filter_location);
		mCategoryLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.active_list_header_filter_category_layout);
		mPriceLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.active_list_header_filter_price_layout);
		mLocationLayout = (RelativeLayout) mHeaderLayout.findViewById(R.id.active_list_header_filter_location_layout);

		mCategoryLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showCategoryPop(v);
			}
		});
		mPriceLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showPricePop(v);
			}
		});
		mLocationLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showProvincePop(v);
			}
		});
	}
	int mIndexMargin = CommonUtil.dip2px(6);
//	public void fillSelectLayout(LinearLayout layout,int position){
//		ImageView image = new ImageView(BaseApplication.mContext);
//		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//		lp.setMargins(mIndexMargin, 0, mIndexMargin, 0);
////		image.setImageResource(R.drawable.active_list_pager_selector);
//		if (position == 0) {
//			image.setSelected(true);
//		}
//		layout.addView(image, lp);
//	}
	
	int mPopMargin = CommonUtil.dip2px(5);
	private PopupWindow mCategoryPopup;
	public void showCategoryPop(View v){
		if (mCategoryPopup != null&& mCategoryPopup.isShowing()) {
			mCategoryPopup.dismiss();
			return;
		} else {
			mCategoryPopup = initPopupWindowView(Dictionary.TYPE_CATEGORY);
			mCategoryPopup.showAsDropDown(v, mPopMargin,CommonUtil.dip2px(1));
		}
	}
	private PopupWindow mPricePopup;
	public void showPricePop(View v){
		if (mPricePopup != null&& mPricePopup.isShowing()) {
			mPricePopup.dismiss();
			return;
		} else {
			mPricePopup = initPopupWindowView(Dictionary.TYPE_PRICE);
			mPricePopup.showAsDropDown(v, mPopMargin,CommonUtil.dip2px(1));
		}
	}
	
	@Click(R.id.active_list_search)
	public void search(){
		ActiveSearchFragment.add(mFragmentId);
	}
	private PopupWindow mProvincePopup;
	public void showProvincePop(View v){
		if (mProvincePopup != null&& mProvincePopup.isShowing()) {
			mProvincePopup.dismiss();
			return;
		} else {
			mProvincePopup = initPopupWindowView(Dictionary.TYPE_PROVINCE);
			mProvincePopup.showAsDropDown(v, mPopMargin,CommonUtil.dip2px(1));
		}
	}
	@SuppressWarnings("unchecked")
	public List<Category> buildCategory(){
		mCategorys = (List<Category>) CategoryManager.getInstance().queryAll();
		if (mCategorys == null && mCategorys.size() == 0) {
			getActiveCategory();
		}
		return mCategorys;
	}
	DictionaryAdapter adapter = new DictionaryAdapter();
	CategoryAdapter mCategoryAdapter = new CategoryAdapter();
	@SuppressWarnings("unchecked")
	@SuppressLint({ "InflateParams", "ClickableViewAccessibility" })
	public PopupWindow initPopupWindowView(final String type) {
		View popupLayout = mInflater.inflate(R.layout.dictionary_popup,null, false);
		ListView listView = (ListView) popupLayout.findViewById(R.id.dictionary_popup_list);
		if (Dictionary.TYPE_CATEGORY.equals(type)) {//初始化分类item
			listView.setAdapter(mCategoryAdapter);
			getActiveCategory();
			mCategoryAdapter.setActionCallBack(new com.tstudy.laoshibang.active.CategoryAdapter.AdapterCallBack() {
				@Override
				public void onItemClick(Category category, int position) {
					mCategoryPopup.dismiss();
					if (category.code.equals(mSelectAllCode)) {
						mSelectCategory = null;
						mCategoryTxt.setText(R.string.active_list_filter_category);
					}else{
						mCategoryTxt.setText(category.name);
						mSelectCategory = category;
						CommonUtil.umengEvent(CONSTANT.EVENT_ID.ACTIVE_CATEGORY,Dictionary.TYPE_CATEGORY,mSelectCategory.name);
					}
					mLoadType = LoadType.load_first;
					getActiveList();
				}
			});
		}else {
			List<Dictionary> list = new ArrayList<Dictionary>();
			listView.setAdapter(adapter);
			if (type.equals(Dictionary.TYPE_PROVINCE)) {//初始化省市item
				list = buildList(Dictionary.TYPE_PROVINCE, null);
			}else{
				list = DictionaryManager.getInstance().queryByField("type", type);
			}
			list.add(0,new Dictionary(mSelectAllKey, mSelectAllStr,type));
			adapter.setData(list);
			adapter.setActionCallBack(new ActionCallBack() {
				@Override
				public void onItemClick(Dictionary dictionary,int position) {
					if (Dictionary.TYPE_PRICE.equals(dictionary.type)) {
						mPricePopup.dismiss();
						if (dictionary.code == mSelectAllKey) {
							mSelectPrice = null;
							mPriceTxt.setText(R.string.active_list_filter_price);
						}else{
							mPriceTxt.setText(dictionary.name);
							mSelectPrice = dictionary;
							CommonUtil.umengEvent(CONSTANT.EVENT_ID.ACTIVE_PRICE_QUERY,Dictionary.TYPE_PRICE,mSelectPrice.name);
						}
					}else if (Dictionary.TYPE_PROVINCE.equals(dictionary.type)) {
						mProvincePopup.dismiss();
						if (dictionary.code == mSelectAllKey) {
							mSelectProvince = null;
							mLocationTxt.setText(R.string.active_list_filter_location);
						}else{
							mSelectProvince = dictionary;
							mLocationTxt.setText(dictionary.name);
							CommonUtil.umengEvent(CONSTANT.EVENT_ID.ACTIVE_POSITION,Dictionary.TYPE_PROVINCE,mSelectProvince.name);
						}
					}
					mLoadType = LoadType.load_first;
					getActiveList();
				}
			});
		}
		final PopupWindow popup = new PopupWindow(popupLayout,BaseApplication.mScreenWidth/3-mPopMargin*2,ViewGroup.LayoutParams.WRAP_CONTENT);
//		popup.setAnimationStyle(R.style.AnimationFade);
		popup.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);           
		popup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);  
		popup.setFocusable(true);  
		popup.setBackgroundDrawable(new BitmapDrawable());  
		popup.setOutsideTouchable(true);
		return popup;
	}
	
	@SuppressWarnings("unchecked")
	public List<Dictionary> buildList(String type,Dictionary dictionary){
		List<City> cityList = null;
		if (Dictionary.TYPE_PROVINCE.equals(type)) {
			cityList = CityManager.getInstance().queryByField("parentProvinceId",0);
		}else if (Dictionary.TYPE_CITY.equals(type)) {
			if (BaseApplication.mLocationCity != null) {
				cityList = CityManager.getInstance().queryByField("parentProvinceId", BaseApplication.mLocationCity.getCityId());
			}else{
//				cityList = CityManager.getInstance().queryByField("parentProvinceId",dictionary.key);
				Map<String, Object> args = new HashMap<String, Object>();
				args.put("parentProvinceId", dictionary.code+"");
				args.put("parentCityId","0");
				cityList = CityManager.getInstance().queryByFields(args);
			}
		}else if (Dictionary.TYPE_COUNTY.equals(type)) {
			cityList = CityManager.getInstance().queryByField("parentCityId",dictionary.code);
		}
		List<Dictionary> dicList = new ArrayList<Dictionary>();
		if (cityList != null) {
			int size = cityList.size();
			for (int i = 0; i < size; i++) {
				Dictionary each = new Dictionary();
				City city = cityList.get(i);
				each.type = city.getType();
				each.code = city.getCityId();
				each.name = city.getCityName();
				dicList.add(each);
			}
		}
		return dicList;
	}
	
	
	
	class ListItemPageAdapter extends PagerAdapter implements OnPageChangeListener{
		List<View> mViewList = new ArrayList<View>();
		public void setData(List<View> viewList){
			mViewList = viewList;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mViewList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}
		
		 @Override  
		    public void destroyItem(ViewGroup container, int position,Object object) {  
			 if(mViewList.size() > 1) {
				 container.removeView(mViewList.get(position));  
			 }else {
				 container.removeView((View)object);
			 }
		    }  

		@Override
		public int getItemPosition(Object object) {
			return POSITION_NONE;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(mViewList.get(position));
			return mViewList.get(position);
		}

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onPageSelected(int position) {
			changeSelectBg(position);
			
		}

		@Override
		public void onPageScrollStateChanged(int state) {
			// TODO Auto-generated method stub
		}
		
	}
	
	public void onEventMainThread(Object object) {
		if(object instanceof ActiveLoveEvent){
			ActiveLoveEvent event = (ActiveLoveEvent) object;
			mActives.get(event.position).isPraise = event.isPrised;
			if (event.isPrised == CONSTANT.IS_PRISED) {
				mActives.get(event.position).praiseNum++;
			}else{
				mActives.get(event.position).praiseNum--;
			}
			
			mActiveListAdapter.setData(mActives);
		}else if(object instanceof ActiveViewEvent){
			ActiveViewEvent event = (ActiveViewEvent) object;
			mActives.get(event.position).accessNum++;
			mActiveListAdapter.setData(mActives);
		}else if(object instanceof ChangeGroupEvent){
			mLoadType = LoadType.load_first;
			if (BaseApplication.mCurrentGroup != null) {
				mTitleTxt.setText(BaseApplication.mCurrentGroup.name +CONSTANT.GROUP_SEPEREATE+ BaseApplication.getResString(R.string.active_list_title));
			}
			getActiveList();
		}
	}

	public void changeSelectBg(int position){
			if (mViewPagerSelectLayout != null) {
//				mViewPagerSelectLayout.getChildAt(position).setSelected(true);
//				mCurrentPosition = position;
//				int childCount = mViewPagerSelectLayout.getChildCount();
//				for (int i = 0; i < childCount; i++) {
//					mViewPagerSelectLayout.getChildAt(i).setSelected(i==position);
//				}
				addCallBacks();
			}
	} 
	
	public void removeCallbacks(){
		mHandler.removeCallbacks(changeHeaderTask);
	}
	
	public void addCallBacks(){
		removeCallbacks();
		mHandler.postDelayed(changeHeaderTask, BANNER_DURATION);
	}
	Runnable changeHeaderTask = new Runnable() {
		@Override
		public void run() {
			int size = mViewList.size();
			mCurrentPosition++;
			if (mCurrentPosition == size) {
				mCurrentPosition = 0;
			}
			mViewPager.setCurrentItem(mCurrentPosition);
		}
	};
	
	/**
	 * 获取活动列表
	 */
	private void getActiveList(){
		if (mIsLoading) {
			return ;
		}
		mIsLoading = true;
		BaseListJsonHandler<ActiveListResponse> response = new BaseListJsonHandler<ActiveListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, ActiveListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.getData() != null && response.getData().getAdverts() != null && response.getData().getAdverts().size() > 0) {
						if(mAdverts != null || mAdverts.size() != 0){
							mAdverts.clear();
						}
						mAdverts = response.getData().getAdverts();
						if (mAdverts != null) {
							fillAdverts();
						}else{
							mViewList.clear();
							mViewPager.setVisibility(View.INVISIBLE);
						}
					}
					if (mLoadType == LoadType.load_more) {
						if (mActives.size() == response.getData().getCount()) {
							mBaseOnScrollListener.mIsEnd = true;
						}
					}else{
						mActives.clear();
					}
					if (response.getData() != null) {
						List<Active> list = response.getData().getList();
						if (list != null) {
							mActives.addAll(list);
						}
						if (mActives.size() > 0) {
							mEmptyLayout.setVisibility(View.GONE);
						}else{
							mEmptyLayout.setVisibility(View.VISIBLE);
						}
						mActiveListAdapter.setData(mActives);
					}
				}else {
					BaseApplication.showToast(response.getErrMsg());
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					ActiveListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected ActiveListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,ActiveListResponse.class);
			}
		};
		List<Conds> conds = new ArrayList<Conds>();
		if (mSelectCategory != null) {
			conds.add(new Conds("clsCode", mSelectCategory.code));
		}
		if (mSelectPrice != null) {
			conds.add(new Conds("isCharge", mSelectPrice.code +""));
		}
		if (mSelectProvince != null) {
			conds.add(new Conds(Dictionary.TYPE_PROVINCE, mSelectProvince.code+""));
		}
//		if (BaseApplication.mCurrentGroup != null) {
//			conds.add(new Conds("groupId",BaseApplication.mCurrentGroup.groupId));
//		}
		int isAdt = 1;
		if (mLoadType == LoadType.load_more) {
			isAdt = 0;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		
		HttpManager.getInstance().getActiveList(BaseApplication.mUserNo,start,limit, null,conds,isAdt,response);
	}
	
	/**
	 * 获取活动类别
	 */
	private void getActiveCategory(){
		BaseListJsonHandler<ActiveCategoryResponse> response = new BaseListJsonHandler<ActiveCategoryResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, ActiveCategoryResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (response.data != null) {
						mCategorys = response.data;
						mCategorys.add(0,new Category(mSelectAllCode,mSelectAllStr));
						mCategoryAdapter.setData(mCategorys);
						CategoryManager.getInstance().insertOrUpdate(response.data);
					}
				}else{
					BaseApplication.showToast(response.getErrMsg());
					afterLoading();
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					ActiveCategoryResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected ActiveCategoryResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,ActiveCategoryResponse.class);
			}
		};
		HttpManager.getInstance().getActiveCategory(BaseApplication.mUserNo,response);
	}
	/**
	 * 活动点赞
	 * @param activeId
	 * @param type
	 * @param isPraise
	 */
	private void loveAction(final Active active,int type,final int isPraise,final TextView loveCountTxt){
		BaseListJsonHandler<CommunityListResponse> response = new BaseListJsonHandler<CommunityListResponse>() {
			public void onStart() {
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, CommunityListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
//					active.isPraise = active.isPraise==1?0:1;
//					int count = active.isPraise==0?active.praiseNum-1:active.praiseNum +1;
//					loveCountTxt.setText(count+"");
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					CommunityListResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected CommunityListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
//				afterLoading();
				return mGson.fromJson(rawJsonData,CommunityListResponse.class);
			}
		};
		HttpManager.getInstance().loveAction(BaseApplication.mUserNo, type, active.actId, isPraise,null, response);
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.active_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}else{
			if (mActives.size() > 0) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.active_no_more_data));
			}else{
				mPullToRefreshListView.dissmissLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	}
	@Click(R.id.active_list_title_opengroup)
	public void showGroupPop() {
		((IndexActivity)getActivity()).showGroupPop();
	}
	@Override
	public void clear() {
		// TODO Auto-generated method stub
		if (mProvincePopup != null) {
			mProvincePopup.dismiss();
		}
		if (mPricePopup != null) {
			mPricePopup.dismiss();
		}
		if (mCategoryPopup != null) {
			mCategoryPopup.dismiss();
		}
		
	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
